package com.baizhi.service.impl;

import com.baizhi.entity.Admin;
import com.baizhi.entity.User;
import com.baizhi.exception.CodeEnum;
import com.baizhi.mapper.AdminMapper;
import com.baizhi.mapper.UserMapper;
import com.baizhi.service.AdminService;
import com.baizhi.utils.MD5Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Locale;
import java.util.UUID;

/**
* @author 16357
* @description 针对表【t_admin】的数据库操作Service实现
* @createDate 2024-08-07 15:39:39
*/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public Boolean addAdmin(User user) {
        //1. 判断管理员信息是否重复
        //1.1 根据用户名查询所有信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",user.getUserName());
        User result = userMapper.selectOne(queryWrapper);
        if(result!=null){
            //用户名被占用
            CodeEnum.username_already_exist.throwException();
        }

        // user 中的密码加密
        //生成盐值
        String salt = UUID.randomUUID().toString().toUpperCase(Locale.ROOT);
        String md5Password = MD5Util.getMd5Password(user.getPassword(),salt);
        user.setPassword(md5Password);
        user.setSalt(salt);
        user.setGmtCreate(new Date());
        user.setGmtModified(new Date());


        //2. 直接添加User
        int userRow = userMapper.insert(user);
        //3. 添加admin
        Admin admin = new Admin();
        admin.setName(user.getRealName());
        admin.setPhone(user.getPhone());
        admin.setAddress(user.getAddress());
        admin.setUserId(user.getPkUid());

        int adminRow = adminMapper.insert(admin);
        if(adminRow == 0 || userRow == 0){
            CodeEnum.user_register_fail.throwException();
        }
        return true;
    }
}




